package com.ktjy.ktmall.servlet;

import com.alibaba.fastjson.JSON;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.common.utils.BinaryUtil;
import com.aliyun.oss.model.MatchMode;
import com.aliyun.oss.model.PolicyConditions;
import com.ktjy.ktmall.entity.AjaxResult;
import com.ktjy.ktmall.service.WxUserService;
import com.ktjy.ktmall.service.impl.WxUserServiceImpl;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Properties;

// 用于获取OSS服务端签名数据
@WebServlet(name = "OSSServlet", urlPatterns = "/uni/oss/policy")
public class OSSServlet extends HttpServlet {

    private String accessKey = null;   // OSS的用户名
    private String secretKey = null; // OSS密钥
    private String endpoint = null; // OSS对外服务的访问域名
    private String bucket = null; // OSS中的一种概念，相当于文件夹名

    // OSS的相关配置参数
    public void getConfigParam() {
        Properties params = new Properties();
        String configFile = "OSSConf.properties";//配置文件路径
        //加载配置文件到输入流中
        InputStream is= OSSServlet.class.getClassLoader().getResourceAsStream(configFile);

        try {
            //从输入流中读取属性列表
            params.load(is);
        } catch (IOException e) {
            e.printStackTrace();
        }
        //根据指定的获取对应的值
        accessKey = params.getProperty("oss.access-key");
        secretKey = params.getProperty("oss.secret-key");
        endpoint = params.getProperty("oss.endpoint");
        bucket = params.getProperty("oss.bucket");
    }

    @Override
    public void init(ServletConfig config) throws ServletException {
        getConfigParam();
    }


    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        Map<String, String> respMap = null;

        String host = "https://" + bucket + "." + endpoint; // host的格式为 bucketname.endpoint
        //这个前缀其实就是一个目录，即会在OSS的文件管理中创建这个目录，后续我们所有上传的文件//都会被保存到这个目录中。
        String format = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
        String dir = format + "/"; // 用户上传文件时指定的前缀。

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKey, secretKey);

        try {
            long expireTime = 30;
            long expireEndTime = System.currentTimeMillis() + expireTime * 1000;
            Date expiration = new Date(expireEndTime);
            // PostObject请求最大可支持的文件大小为5 GB，即CONTENT_LENGTH_RANGE为5*1024*1024*1024。
            PolicyConditions policyConds = new PolicyConditions();
            policyConds.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, 0, 1048576000);
            policyConds.addConditionItem(MatchMode.StartWith, PolicyConditions.COND_KEY, dir);

            String postPolicy = ossClient.generatePostPolicy(expiration, policyConds);
            byte[] binaryData = postPolicy.getBytes("utf-8");
            String encodedPolicy = BinaryUtil.toBase64String(binaryData);
            String postSignature = ossClient.calculatePostSignature(postPolicy);

            respMap = new LinkedHashMap<String, String>();
            respMap.put("ossAccessId", accessKey);
            respMap.put("ossPolicy", encodedPolicy);
            respMap.put("ossSignature", postSignature);  // 防伪签名
            respMap.put("ossKey", dir + new Date().getTime() + ".png");
            respMap.put("host", host);
            respMap.put("expire", String.valueOf(expireEndTime / 1000));

        } catch (Exception e) {
            System.out.println(e.getMessage());
        } finally {
            ossClient.shutdown();
        }
        // 创建out对象
        PrintWriter out = response.getWriter();
        out.print(JSON.toJSONString(AjaxResult.success("OSS服务端签名数据获取成功!",respMap)));
        out.flush();
        out.close();
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}
